package com.mingqijia.gassafety.webserver.service.workorder.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gap.basic.base.CommonResponse;
import com.mingqijia.gassafety.db.entity.ServiceCombo;
import com.mingqijia.gassafety.db.entity.ServiceComboDetail;
import com.mingqijia.gassafety.db.entity.ServiceComboOrder;
import com.mingqijia.gassafety.db.entity.WorkOrderHistory;
import com.mingqijia.gassafety.db.mapper.ServiceComboOrderMapper;
import com.mingqijia.gassafety.webserver.request.inner.ServiceComboRecordRequest;
import com.mingqijia.gassafety.webserver.request.inner.ServiceComboSyncRequest;
import com.mingqijia.gassafety.webserver.request.ServiceComboDetailAddRequest;
import com.mingqijia.gassafety.webserver.request.inner.SyncOrderDataRespose;
import com.mingqijia.gassafety.webserver.response.inner.ServiceComboRecordRespose;
import com.mingqijia.gassafety.webserver.service.ServiceComboDetailService;
import com.mingqijia.gassafety.webserver.service.ServiceComboService;
import com.mingqijia.gassafety.webserver.service.workorder.SyncServiceComboService;
import com.mingqijia.gassafety.webserver.service.workorder.WorkOrderHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SyncServiceComboServiceImpl implements SyncServiceComboService {

    @Autowired
    private ServiceComboService serviceComboService;

    @Autowired
    private ServiceComboDetailService serviceComboDetailService;

    @Autowired
    private ServiceComboOrderMapper serviceComboOrderMapper;

    @Autowired
    private WorkOrderHistoryService workOrderHistoryService;

    private final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Transactional(rollbackFor = Exception.class)
    @Override
    public CommonResponse<Boolean> syncCombo(List<ServiceComboSyncRequest> request) {
        if (CollectionUtils.isNotEmpty(request)) {
            try {
                //根据账单编号判断是否为新增还是修改
                List<String> billCodes = request.stream().map(ServiceComboSyncRequest::getBillCode).collect(Collectors.toList());
                List<String> orderCodes = request.stream().map(ServiceComboSyncRequest::getOrderCode).collect(Collectors.toList());
                List<ServiceCombo> serviceCombos = serviceComboService.queryByBillCode(billCodes);
                List<ServiceComboDetail> comboDetails = serviceComboDetailService.queryByOrderCode(orderCodes);
                Map<String, ServiceCombo> serviceComboMap = new HashMap<>();
                Map<String, List<ServiceComboDetail>> orderCodeMap = new HashMap<>();
                //新增集合
                List<ServiceCombo> addServiceCombos = new ArrayList<>();
                //修改集合
                List<ServiceCombo> updateServiceCombos = new ArrayList<>();

                //新增详情集合
                List<ServiceComboDetail> addCombosDetailList = new ArrayList<>();
                if (CollectionUtils.isNotEmpty(serviceCombos)) {
                    serviceComboMap = serviceCombos.stream().collect(Collectors.toMap(ServiceCombo::getBillCode, ServiceCombo -> ServiceCombo, (a1,a2) -> a1));
                }
                if (CollectionUtils.isNotEmpty(comboDetails)) {
                    orderCodeMap = comboDetails.stream().collect(Collectors.groupingBy(ServiceComboDetail::getOrderCode));
                }
                for (ServiceComboSyncRequest comboAddRequest : request) {
                    if (serviceComboMap.containsKey(comboAddRequest.getBillCode())) {
                        ServiceCombo serviceCombo = serviceComboMap.get(comboAddRequest.getBillCode());
                        serviceCombo.setOrderState(comboAddRequest.getOrderState());
                        serviceCombo.setPayState(comboAddRequest.getPayState());
                        serviceCombo.setUpdatedAt(new Date());
                        serviceCombo.setSpId(comboAddRequest.getOrgCode());
                        updateServiceCombos.add(serviceCombo);
                    } else {
                        ServiceCombo serviceCombo = new ServiceCombo();
                        BeanUtils.copyProperties(comboAddRequest, serviceCombo);
                        serviceCombo.setStartTime(format.parse(comboAddRequest.getStartTime()));
                        serviceCombo.setEndTime(format.parse(comboAddRequest.getEndTime()));
                        serviceCombo.setCreatedAt(new Date());
                        serviceCombo.setIsDeleted(false);
                        serviceCombo.setUpdatedAt(new Date());
                        serviceCombo.setSpId(comboAddRequest.getOrgCode());
                        addServiceCombos.add(serviceCombo);
                    }
                    for (ServiceComboDetailAddRequest detailAddRequest : comboAddRequest.getPkgServiceList()) {
                        if (!orderCodeMap.containsKey(detailAddRequest.getOrderCode())) {
                            ServiceComboDetail detail = new ServiceComboDetail();
                            BeanUtils.copyProperties(detailAddRequest, detail);
                            detail.setSpId(detailAddRequest.getOrgCode());
                            addCombosDetailList.add(detail);
                        }
                    }
                }
                if (CollectionUtils.isNotEmpty(addServiceCombos)){
                    serviceComboService.addCombo(addServiceCombos);
                }
                if (CollectionUtils.isNotEmpty(updateServiceCombos)){
                    serviceComboService.updateCombo(updateServiceCombos);
                }
                if (CollectionUtils.isNotEmpty(addCombosDetailList)){
                    serviceComboDetailService.addComboDetail(addCombosDetailList);
                }
            } catch (ParseException e) {
                log.error("同步服务套餐信息报错", e);
                return CommonResponse.failure("系统异常");
            }

        }
        return CommonResponse.success(true);
    }

    @Override
    public List<ServiceComboRecordRespose> serviceLogs(ServiceComboRecordRequest request) {
        List<ServiceComboRecordRespose> resposeList = new ArrayList<>();
        //根据条件查询订单信息
        List<ServiceComboDetail> comboDetails = serviceComboDetailService.queryByRecord(request);
        if (CollectionUtils.isNotEmpty(comboDetails)) {
            List<Integer> detailIds = comboDetails.stream().map(ServiceComboDetail::getId).collect(Collectors.toList());
            QueryWrapper<ServiceComboOrder> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.lambda().in(ServiceComboOrder::getComboDetailId, detailIds)
                    .eq(ServiceComboOrder::getIsDeleted, 0);
            List<ServiceComboOrder> comboOrders = serviceComboOrderMapper.selectList(orderQueryWrapper);
            if (CollectionUtils.isNotEmpty(comboOrders)) {
                List<String> orderNos = comboOrders.stream().map(ServiceComboOrder::getThirdOrderNo).collect(Collectors.toList());
                List<WorkOrderHistory> orderHistories = workOrderHistoryService.queryByOrderNo(orderNos);
                Map<String, Integer> orderMap = new HashMap<>();
                if (CollectionUtils.isNotEmpty(orderHistories)) {
                    orderMap = orderHistories.stream().collect(Collectors.toMap(WorkOrderHistory::getOrderNo, WorkOrderHistory::getHandleStatus));
                }
                for (ServiceComboOrder order : comboOrders) {
                    ServiceComboRecordRespose recordRespose = new ServiceComboRecordRespose();
                    recordRespose.setId(order.getId());
                    recordRespose.setOrderId(order.getThirdOrderId());
                    recordRespose.setOrderCode(order.getThirdOrderNo());
                    recordRespose.setCode(order.getCode());
                    recordRespose.setAlarmTime(order.getAlarmTime());
                    recordRespose.setAlarmTimeStr(format.format(order.getAlarmTime()));
                    if (orderMap.containsKey(order.getThirdOrderNo())) {
                        Integer status = orderMap.get(order.getThirdOrderNo());
                        recordRespose.setStatus(String.valueOf(status));
                        recordRespose.setStatusStr(status != null && status == 1? "已完成":"未完成");
                    }

                    String orderExt = order.getThirdOrderExt();
                    if (StringUtils.isNotBlank(orderExt)) {
                        JSONObject jsonObject = JSONObject.parseObject(orderExt);
                        //recordRespose.setVisitTime(orderExt);
                        if (jsonObject != null) {
                            recordRespose.setVisitTimeStr(jsonObject.getString("serviceBeginTime"));
                            recordRespose.setVisitPerson(jsonObject.getString("visitPerson"));
                            recordRespose.setContact(jsonObject.getString("contact"));
                        }
                    }
                    resposeList.add(recordRespose);
                }
            }
        }
        return resposeList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public CommonResponse<Boolean> syncOrderData(SyncOrderDataRespose request) {
        QueryWrapper<ServiceComboOrder> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.lambda().eq(ServiceComboOrder::getThirdOrderNo, request.getOrderCode())
                .eq(ServiceComboOrder::getIsDeleted, 0);
        List<ServiceComboOrder> comboOrders = serviceComboOrderMapper.selectList(orderQueryWrapper);
        if (CollectionUtils.isNotEmpty(comboOrders)) {
            try {
                for (ServiceComboOrder comboOrder : comboOrders) {
                    comboOrder.setThirdOrderStatus(request.getStatus());
                    comboOrder.setThirdOrderExt(request.toString());
                    serviceComboOrderMapper.updateById(comboOrder);
                    //TODO 看师傅帮个忙完工工单状态是多少，完工时需要把工单状态改为已完成
                    if (request.getStatus().equals("1")) {
                        workOrderHistoryService.updateHandleStatus(request.getOrderCode(), 1, format.parse(request.getServiceEndTime()));
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage());
                return CommonResponse.failure(e.getMessage());
            }
            return CommonResponse.success(true);
        }
        return CommonResponse.failure("工单不存在");
    }
}
